package com.feng.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feng.chat.common.Common;
import com.feng.chat.dto.Result;
import com.feng.chat.dto.TalkListDTO;
import com.feng.chat.entity.*;
import com.feng.chat.mapper.*;
import com.feng.chat.service.IContactService;
import com.feng.chat.service.ITalkRecordsService;
import com.feng.chat.service.ITalkSessionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.chat.service.IUsersService;
import com.feng.chat.utils.GetUserUtil;
import com.feng.chat.utils.MessageUtil;
import com.feng.chat.vo.TalkCreateVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户聊天列表 服务实现类
 * </p>
 *
 * @author dyf
 * @since 2022-05-31
 */
@Service
public class TalkSessionServiceImpl extends ServiceImpl<TalkSessionMapper, TalkSession> implements ITalkSessionService {

    @Autowired
    private TalkSessionMapper talkSessionMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private ContactMapper contactMapper;

    @Autowired
    private TalkRecordsMapper talkRecordsMapper;

    @Autowired
    private GroupMapper groupMapper;

    /**
     * 获取会话列表
     *
     * @param id
     * @return
     */
    @Override
    public Result TalkList(Integer id) {
        List<TalkListDTO> talkListDTOS = new ArrayList<>();

        /*QueryWrapper<TalkSession> talkSessionQueryWrapper = new QueryWrapper<>();
        talkSessionQueryWrapper.eq("receiver_id",id).eq("is_delete",0).orderByDesc("updated_at");
        List<TalkSession> friendList = list(talkSessionQueryWrapper);*/

        List<TalkSession> sessionList = talkSessionMapper.getSessionList(id);

        talkListDTOS = sessionList.stream().map(item -> {
            TalkListDTO talkListDTO = new TalkListDTO();

            talkListDTO.setId(item.getId());
            talkListDTO.setTalk_type(item.getTalkType());
            talkListDTO.setIs_top(item.getIsTop());
            talkListDTO.setIs_robot(item.getIsRobot());
            talkListDTO.setIs_disturb(item.getIsDisturb());
            if (item.getTalkType() == 1) {

                Users users;
                if (item.getUserId() == id) {
                    users = usersMapper.selectById(item.getReceiverId());
                } else {
                    users = usersMapper.selectById(item.getUserId());
                }

                talkListDTO.setName(users.getNickName());
                talkListDTO.setAvatar(users.getAvatar());
                talkListDTO.setReceiver_id(users.getId());
                Integer onLine = GetUserUtil.isOnLine(users.getId());
                talkListDTO.setIs_online(onLine);

                QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
                contactQueryWrapper.eq("user_id", id).eq("friend_id", users.getId());
                Contact contact = contactMapper.selectOne(contactQueryWrapper);
                if (contact == null || contact.getStatus() == 1) {
                    talkListDTO.setRemark_name("");
                } else {
                    talkListDTO.setRemark_name(contact.getRemark());
                }

                //最后一条消息
                TalkRecords talkRecords = talkRecordsMapper.getLastMessage(item.getTalkType(), id, users.getId());

                if (talkRecords!=null){
                    talkListDTO.setUpdated_at(talkRecords.getUpdatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
                    talkListDTO.setMsg_text(MessageUtil.getMessageType(talkRecords.getMsgType(), talkRecords.getContent()));
                }

                QueryWrapper<TalkRecords> talkRecordsQueryWrapper = new QueryWrapper<>();
//            talkRecordsQueryWrapper.eq("is_read",0).eq("is_revoke",0).eq("user_id",users.getId()).eq("receiver_id",id);
                talkRecordsQueryWrapper.ne("msg_type", 7).eq("talk_type",1).eq("is_revoke",0).eq("user_id", users.getId()).eq("receiver_id", id).eq("is_read", 0);
                long unRead = talkRecordsMapper.selectCount(talkRecordsQueryWrapper);
                talkListDTO.setUnread_num(unRead);
            } else {
                GroupChat groupChat = groupMapper.selectById(item.getReceiverId());

                talkListDTO.setName(groupChat.getGroupName());
                talkListDTO.setAvatar(groupChat.getAvatar());
                talkListDTO.setReceiver_id(groupChat.getId());

                TalkRecords groupLastMessage = talkRecordsMapper.getGroupLastMessage(id, item.getTalkType(), item.getReceiverId());
                talkListDTO.setUpdated_at(groupLastMessage.getUpdatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
                talkListDTO.setMsg_text(MessageUtil.getMessageType(groupLastMessage.getMsgType(), groupLastMessage.getContent()));

                QueryWrapper<TalkRecords> talkRecordsQueryWrapper = new QueryWrapper<>();
//            talkRecordsQueryWrapper.eq("is_read",0).eq("is_revoke",0).eq("user_id",users.getId()).eq("receiver_id",id);
                talkRecordsQueryWrapper.ne("msg_type", 7).eq("is_revoke",0).eq("talk_type",2).eq("receiver_id", item.getReceiverId());

                long unRead = 0;

                List<TalkRecords> talkRecords = talkRecordsMapper.selectList(talkRecordsQueryWrapper);
                for (TalkRecords talkRecord : talkRecords) {
                    if (talkRecord.getGroupRead()!=null){
                        List<String> read_ids = Arrays.asList(talkRecord.getGroupRead().split(","));
                        if (!read_ids.contains(id.toString())){
                            unRead++;
                        }
                    }else {
                        unRead++;
                    }
                }

                talkListDTO.setUnread_num(unRead);
            }

            return talkListDTO;
        }).collect(Collectors.toList());


        return Result.success(talkListDTOS);
    }

    /**
     * 创建会话
     *
     * @param id
     * @param talkCreateVO
     * @return
     */
    @Override
    public Result create(Integer id, TalkCreateVO talkCreateVO) {

        TalkSession talkSession = null;
        talkSession = talkSessionMapper.getSession(id, talkCreateVO.getReceiver_id());
        if (talkSession == null) {
            TalkSession session = new TalkSession();
            session.setTalkType(talkCreateVO.getTalk_type());
            session.setReceiverId(talkCreateVO.getReceiver_id());
            session.setUserId(id);
            boolean save = save(session);
            talkSession = session;
        } else {
            if (talkSession.getIsDelete() == 1) {
                talkSession.setIsDelete(0);
                boolean update = updateById(talkSession);
            }
        }

        TalkListDTO talkListDTO = new TalkListDTO();
        talkListDTO.setId(talkSession.getId());
        talkListDTO.setTalk_type(talkSession.getTalkType());
        talkListDTO.setIs_top(talkSession.getIsTop());
        talkListDTO.setIs_robot(talkSession.getIsRobot());
        talkListDTO.setIs_disturb(talkSession.getIsDisturb());


        if (talkSession.getTalkType() == 1) {

            Users users;
            if (talkSession.getUserId() == id) {
                users = usersMapper.selectById(talkSession.getReceiverId());
            } else {
                users = usersMapper.selectById(talkSession.getUserId());
            }

            talkListDTO.setName(users.getNickName());
            talkListDTO.setAvatar(users.getAvatar());
            talkListDTO.setReceiver_id(users.getId());

            QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
            contactQueryWrapper.eq("user_id", id).eq("friend_id", users.getId());
            Contact contact = contactMapper.selectOne(contactQueryWrapper);
            if (contact == null || contact.getStatus() == 1) {
                talkListDTO.setRemark_name("");
            } else {
                talkListDTO.setRemark_name(contact.getRemark());
            }

            //最后一条消息
            TalkRecords talkRecords = talkRecordsMapper.getLastMessage(talkSession.getTalkType(), id, users.getId());

            talkListDTO.setUpdated_at(talkRecords.getUpdatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
            talkListDTO.setMsg_text(MessageUtil.getMessageType(talkRecords.getMsgType(), talkRecords.getContent()));

            QueryWrapper<TalkRecords> talkRecordsQueryWrapper = new QueryWrapper<>();
//            talkRecordsQueryWrapper.eq("is_read",0).eq("is_revoke",0).eq("user_id",users.getId()).eq("receiver_id",id);
            talkRecordsQueryWrapper.ne("msg_type", 7).eq("is_revoke",0).eq("talk_type",2).eq("user_id", users.getId()).eq("receiver_id", id);
            long unRead = talkRecordsMapper.selectCount(talkRecordsQueryWrapper);
            talkListDTO.setUnread_num(unRead);
        } else {
            GroupChat groupChat = groupMapper.selectById(talkCreateVO.getReceiver_id());

            talkListDTO.setName(groupChat.getGroupName());
            talkListDTO.setAvatar(groupChat.getAvatar());
            talkListDTO.setReceiver_id(groupChat.getId());

            TalkRecords groupLastMessage = talkRecordsMapper.getGroupLastMessage(id, talkSession.getTalkType(), talkCreateVO.getReceiver_id());
            talkListDTO.setUpdated_at(groupLastMessage.getUpdatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
            talkListDTO.setMsg_text(MessageUtil.getMessageType(groupLastMessage.getMsgType(), groupLastMessage.getContent()));

            QueryWrapper<TalkRecords> talkRecordsQueryWrapper = new QueryWrapper<>();
//            talkRecordsQueryWrapper.eq("is_read",0).eq("is_revoke",0).eq("user_id",users.getId()).eq("receiver_id",id);
            talkRecordsQueryWrapper.ne("msg_type", 7).eq("is_revoke",0).eq("talk_type",2).eq("receiver_id", talkCreateVO.getReceiver_id());

            long unRead = 0;

            List<TalkRecords> talkRecords = talkRecordsMapper.selectList(talkRecordsQueryWrapper);
            for (TalkRecords talkRecord : talkRecords) {
                if (talkRecord.getGroupRead()!=null){
                    List<String> read_ids = Arrays.asList(talkRecord.getGroupRead().split(","));
                    if (!read_ids.contains(id.toString())){
                        unRead++;
                    }
                }else {
                    unRead++;
                }

            }
            talkListDTO.setUnread_num(unRead);
        }

/*        QueryWrapper<TalkRecords> talkRecordsQueryWrapper = new QueryWrapper<>();
//            talkRecordsQueryWrapper.eq("is_read",0).eq("is_revoke",0).eq("user_id",users.getId()).eq("receiver_id",id);
        talkRecordsQueryWrapper.ne("msg_type",7).eq("user_id",users.getId()).eq("receiver_id",id);
        long unRead = talkRecordsMapper.selectCount(talkRecordsQueryWrapper);
        talkListDTO.setUnread_num(unRead);*/


        return Result.success(talkListDTO);
    }

    /**
     * 删除会话
     *
     * @param sessionId
     * @return
     */
    @Override
    public Result delete(Integer sessionId) {
        TalkSession talkSession = new TalkSession();
        talkSession.setId(sessionId);
        talkSession.setIsDelete(1);
        boolean update = updateById(talkSession);
        return Result.success();
    }

    /**
     * 设置群免打扰状态
     *
     * @param uid
     * @param is_disturb
     * @param receiver_id
     * @param talk_type
     * @return
     */
    @Override
    public Result disturb(Integer uid, Integer is_disturb, Integer receiver_id, Integer talk_type) {
        QueryWrapper<TalkSession> talkSessionQueryWrapper = new QueryWrapper<>();

        talkSessionQueryWrapper.eq("talk_type", talk_type).eq("user_id", uid).eq("receiver_id", receiver_id);
        TalkSession talkSession = talkSessionMapper.selectOne(talkSessionQueryWrapper);
        if (talkSession != null) {
            talkSession.setIsDisturb(is_disturb);
            talkSessionMapper.updateById(talkSession);
            return Result.success();
        }
        return Result.fail();
    }

    /**
     * 会话列表置顶
     *
     * @param list_id
     * @param type
     * @return
     */
    @Override
    public Result topping(Integer list_id, Integer type) {
        TalkSession talkSession = talkSessionMapper.selectById(list_id);
        if (talkSession != null) {
            talkSession.setIsTop(type);
            talkSessionMapper.updateById(talkSession);
            return Result.success();
        }
        return Result.fail();
    }
}
